package com.jhgsys.internal.sypq.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.sypq.entity.Customer;
import com.jhgsys.internal.sypq.entity.Notice;
import com.jhgsys.internal.sypq.mapper.CustomerMapper;
import com.jhgsys.internal.sypq.service.ICustomerService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.sypq.service.INoticeService;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.entity.UserRole;
import com.jhgsys.internal.system.service.IUserRoleService;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import com.jhgsys.internal.common.entity.FebsConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 客户信息 Service实现
 *
 * @author ganjun
 * @date 2024-11-12 14:15:30
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    @Resource
    private IDictService dictService;

    @Resource
    private INoticeService noticeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 查询（分页）
     * @author ganjun
     * @date 2024-11-12 14:15:30
     * @param request QueryRequest
     * @param customer customer
     * @return IPage<Customer>
    */
    @Override
    public IPage<Customer> findCustomerPage(QueryRequest request, String nameSearch, String contactSearch, String statusSearch, String userName) {
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getDeletedFlg, 0);
        //非系统管理员只可查看自己创建的客户信息

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<UserRole> userRoles = userRoleService.getUserRoleListByUserid(user.getUserId());
        if(CollectionUtil.isNotEmpty(userRoles)){
            //判断是否有系统管理员角色
            boolean isAdmin = userRoles.stream().anyMatch(userRole -> Objects.equals(userRole.getRoleId(), "1"));
            if(isAdmin){
                userName = "";
            }else{
                //判断是否包含项目经理角色
                boolean isPm = userRoles.stream().anyMatch(userRole -> Objects.equals(userRole.getRoleId(), "36452c0006d83ec81491953ab53d651b"));
                if(isPm){
                    userName = user.getUserName();
                }
            }
        }
        if(StringUtils.isNotEmpty(userName)){
            queryWrapper.eq(Customer::getCreatedBy, userName);
        }
        //单位名称，模糊查询
        if(StringUtils.isNotEmpty(nameSearch)){
            queryWrapper.like(Customer::getCustName, nameSearch);
        }
        //联系人，模糊查询
        if(StringUtils.isNotEmpty(contactSearch)){
            queryWrapper.like(Customer::getContact, contactSearch);
        }
        //状态，精确查询
        if(StringUtils.isNotEmpty(statusSearch)){
            queryWrapper.eq(Customer::getStatus, statusSearch);
        }
        queryWrapper.orderByDesc(Customer::getCreatedTime);
        Page<Customer> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        return this.page(page, queryWrapper);
    }

    /**
     * 查询（所有）
     * @author ganjun
     * @date 2024-11-12 14:15:30
     * @param customer customer
     * @return List<Customer>
     */
    @Override
    public List<Customer> findCustomerList(Customer customer) {
	    LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getDeletedFlg, 0);
        queryWrapper.orderByDesc(Customer::getCreatedTime);
        if(customer.getStatus()!=null){
            queryWrapper.eq(Customer::getStatus,customer.getStatus());
        }
        //单位名称
        if(StringUtils.isNotEmpty(customer.getCustName())){
            queryWrapper.like(Customer::getCustName, customer.getCustName());
        }
        //联系人
        if(StringUtils.isNotEmpty(customer.getContact())){
            queryWrapper.like(Customer::getContact, customer.getContact());
        }
        //状态
        if(customer.getStatus() != null){
            queryWrapper.eq(Customer::getStatus, customer.getStatus());
        }

		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author ganjun
    * @date 2024-11-12 14:15:30
    * @param id
    * @return Customer
    */
    @Override
    public Customer findCustomerById(String id){
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     * @author ganjun
     * @date 2024-11-12 14:15:30
     * @param customer customer
     */
    @Override
    @Transactional
    public boolean createCustomer(Customer customer) {
        customer.setStatus(0);
        customer.setStatusName("待审核");
        customer.setDeletedFlg("0");
        boolean res = this.save(customer);
        //待办通知
        if(res){
            String content = "("+customer.getCustName()+")客户信息更新待审核" ;
            Notice notice = new Notice();
            notice.setNoticeType(2);
            notice.setPendingType("客户信息提交审核通知");
            notice.setNoticeTitle("客户信息提交审核通知");
            notice.setNoticeContent(content);
            //客户审核，待办发给系统管理员
            List<User> userByRole = userService.findByRoleId("1", "0");
            if(CollectionUtil.isNotEmpty(userByRole)){
                notice.setReceiveUserId(userByRole.stream().map(User::getUserId).collect(Collectors.joining(",")));
                notice.setReceiveRealName(userByRole.stream().map(User::getUname).collect(Collectors.joining(",")));
            }
            notice.setSendDate(new Date());
            notice.setUrl("/customer");
            notice.setBizId(customer.getId());
            noticeService.createNotice(notice);
        }
        return res;
    }

    /**
     * 修改
     * @author ganjun
     * @date 2024-11-12 14:15:30
     * @param customer customer
     */
    @Override
    @Transactional
    public boolean updateCustomer(Customer customer) {
        if(customer != null && customer.getStatus() != null && customer.getStatus() == 2){
            customer.setStatus(0);
        }
        customer.setStatusName(dictService.findDictLabel("CUST_STATUS", "0"));
        boolean res = this.updateById(customer);
        return res;
    }

    /**
     * 审核
     * @author ganjun
     * @date 2024-11-12 14:15:30
     * @param customer customer
     */
    @Override
    @Transactional
    public boolean auditCustomer(Customer customer) {
        customer.setStatusName(dictService.findDictLabel("CUST_STATUS", customer.getStatus() + ""));
        boolean res = this.updateById(customer);
        if(res){
            try{
                //将审核通知置为已读
                Notice dealNotice = new Notice();
                dealNotice.setBizId(customer.getId());
                dealNotice.setNoticeTitle("客户信息提交审核通知");
                noticeService.dealDone(dealNotice);
                //审核结果通知
                Customer c = this.getById(customer.getId());
                String content = "";
                Notice notice = new Notice();
                if(customer.getStatus() == 1){
                    notice.setNoticeType(1);
                    content = "("+c.getCustName()+")客户信息审核已通过";
                    notice.setNoticeTitle("审核通过");
                }else if(customer.getStatus() == 2){
                    notice.setNoticeType(1);
                    content = "("+c.getCustName()+")客户信息审核未通过(原因："+customer.getOpinion()+")，请及时修改";
                    notice.setUrl("/customer");
                    notice.setNoticeTitle("审核不通过");
                }
                notice.setPendingType("客户信息审核结果");
                notice.setNoticeContent(content);
                User user = userService.findUserDetail(c.getCreatedBy());
                notice.setReceiveUserId(user.getUserId());
                notice.setReceiveRealName(user.getUname());
                notice.setSendDate(new Date());

                noticeService.createNotice(notice);
            }catch(Exception e){
                log.error("updateCustomer: notice error:", e);
            }

        }
        return res;
    }

    /**
     * 逻辑删除
     * @author ganjun
     * @date 2024-11-12 14:15:30
     * @param customer customer
     * @param customerIds customerIds
     */
    @Override
    @Transactional
    public boolean deleteCustomer(Customer customer,String customerIds) {
        boolean result = false;
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> list = Arrays.asList(customerIds.split(StringPool.COMMA));

        customer.setDeletedBy(user.getUserName());
        customer.setDeletedTime(new Date());
        customer.setDeletedFlg(FebsConstant.INVALID);
        int update = this.baseMapper.update(customer,new LambdaQueryWrapper<Customer>().in(Customer::getId,list));
        if (update > 0 ){
            result = true;
        }
        return result;
	}

    /**
    * 物理删除
    * @author ganjun
    * @date 2024-11-12 14:15:30
    * @param customerIds customerIds
    */
    @Override
    @Transactional
    public boolean physicallyDeleteCustomer(String customerIds) {
        List<String> list = Arrays.asList(customerIds.split(StringPool.COMMA));
        LambdaQueryWrapper<Customer> wapper = new LambdaQueryWrapper<>();
        wapper.in(Customer::getId,list);
        return this.remove(wapper);
    }


}
